<?php

namespace App\Http\Controllers\Front;

use App\Model\Cards;
use App\Model\InterPushMatchUser;
use App\Model\InterPushUserInfo;
use App\Model\UserDetail;
use App\User;
use App\Model\InterPushUserMessageRemind;
use App\Model\WeChat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * Class InterPushController
 * @package App\Http\Controllers\Front
 */
class InterPushController extends Controller
{

    /**
     *  修改是否启用禁用
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function isEnabledInterPushUserInfo(Request $request)
    {
        $user = $request->user();
        $interPushUserInfo = $user->interPushUserInfo;

        if ($request->query('is_enabled')) {
            $interPushUserInfo->is_enabled = $request->input('is_enabled');
            $interPushUserInfo->save();
            return $this->renderJson(['is_enabled' => $interPushUserInfo->is_enabled]);
        }
        return $this->renderJson(['is_enabled' => $interPushUserInfo->is_enabled]);
    }


    /**
     * 判断有没有图片
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function judgeInterPushUserInfoImg(Request $request)
    {
        $user = $request->user();
        $interPushUserInfo = $user->interPushUserInfo;
        if ($interPushUserInfo->is_enabled == 0) {
            return $this->renderJson([], -1, '没有开启互推圈的功能！');
        }
        if ($user->interPushUserInfo && $user->interPushUserInfo->weixin_img) {
            return $this->renderJson(['is_exits' => true]);
        } else {
            return $this->renderJson(['is_exits' => false], 0, '没有图片！');
        }
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function saveInterPushUserInfoImg(Request $request)
    {
        $this->validate($request, [
            'img_path' => 'required'
        ], [
            'required' => ':attribute不能为空',
        ], [
            'img_path' => '微信二维码'
        ]);

        $img_path = $request->input('img_path');
        $inter_push_info = InterPushUserInfo::where('user_id', $request->user()->id)->first();
        if ($inter_push_info->weixin_img != null) {
            return $this->fail('你已经上传过了,如需修改请联系客服');
        }

        $inter_push_info->user_id = $request->user()->id;
        $inter_push_info->weixin_img = $img_path;
        $res = $inter_push_info->save();

//        $user = $request->user();
//        $inter_push_info = $user->interPushUserInfo;
//        $inter_push_info->weixin_img = $img_path;
//        $inter_push_info->save();

        // TODO redis sadd 20180604_match_user_1 interpush_user_info_id;sadd 20180604_match_user_2 interpush_user_info_id; sadd 20180604_match_user_3 interpush_user_info_id
        $name1 = date('Ymd') . '_0_' . 'match_user';

        $redis = Redis::connection();
        $redis->rpush($name1, $inter_push_info->id);
        if (!$res) {
            return $this->error();
        }

        return $this->success();
    }

    /**
     * 获取用户互推信息
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function InterPushUserInfo(Request $request)
    {
        $user = $request->user();
        $type = $request->input('type');
        $data = [];
        if ($type == 'edit') {
            if ($me_province = $request->input('me_province')) {
                $user->interPushUserInfo->me_province = $me_province;
                $user->interPushUserInfo->me_province_id = $request->input('me_province_id');
            }
            if ($he_province = $request->input('he_province')) {
                $user->interPushUserInfo->he_province = $he_province;
                $user->interPushUserInfo->he_province_id = $request->input('he_province_id');
            }
            if ($interpush_type = $request->input('interpush_type')) {
                $user->interPushUserInfo->interpush_type = $interpush_type;
            }
            if ($interpush_article = $request->input('interpush_article')) {
                $user->interPushUserInfo->interpush_article = $interpush_article;
            }
            $user->interPushUserInfo->save();
        }
        $user_push_info = $user->interPushUserInfo;

        $article = [];
        if ($user_push_info->interpush_type == 2) {

            $user_article = \DB::table('articles')->where('id', $user_push_info->interpush_article)->first();
            if ($user_push_info) {
                $article = [
                    'uuid' => $user_article->id,
                    'title' => $user_article->title,
                    'cover_path' => $user_article->cover_path,
                    'created_at' => $user_article->created_at,
                    'actual_pageviews' => $user_article->actual_pageviews
                ];
            } else {
                $article = [];
            }
        } else {
            // personal_page_template_user
            if ($template1 = \DB::table("personal_page_template_user")->select("*")->where("id", $user_push_info->interpush_article)->first()){
                $article = $template1;
            }else{
                if ($template2 = \DB::table('personal_page_template_user')->where("user_id", $user->id)->where('is_default',1)->first()){
                    $article = $template2;
                }elseif($template3 = \DB::table('personal_page_template_user')->where("user_id", $user->id)->orderBy("created_at", 'desc')->first()){
                    $push_info = InterPushMatchUser::where("user_id", $user_push_info->id)->first();
                    $push_info->interpush_article = $template3->id;
                    $push_info->save();
                    $article = $template3;
                }
            }
        }

        $interPushMatchUser = new InterPushMatchUser();
        $data = [
            'id' => $user_push_info->id,
            'user_id' => $user_push_info->user_id,
            'weixin_img' => $user_push_info->weixin_img,
            'me_province' => $user_push_info->me_province,
            'he_province' => $user_push_info->he_province,
            'interpush_type' => $user_push_info->interpush_type,
            'interpush_article' => $user_push_info->interpush_article,
            'match_num' => $user_push_info->match_num,
            'created_at' => $user_push_info->created_at->format('Y-m-d H:i:s'),
            'num' => $interPushMatchUser->getInterPushMatchUser($user->id),
            'article' => $article,

        ];
        return $this->renderJson($data);
    }


    /**
     * 获取用户互推信息列表
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function getInterPushMatchUserList(Request $request)
    {
        $user = $request->user();
        $data = [];
        $items = InterPushMatchUser::where(['user_id' => $user->id, 'share' => 0])->get();

        foreach ($items as $item) {
            $data[] = [
                'id' => $item['id'],
                'match_user_id' => $item['match_user_id'],
                'interpush_type' => $item['match_interpush_type'],
                'interpush_article' => $item['match_interpush_article'],
                'is_share' => $item['match_share'],
                'created_at' => $item['created_at']
            ];
        }
        return $this->interPushMatchUserInfo($data);
    }

    /**
     * 匹配互推用户
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function interPushMatchUser(Request $request)
    {
        $user = $request->user();

        $newInterPushMachUserInfo = new InterPushMatchUser();

        $interPushMatchUserInfo = $newInterPushMachUserInfo->addMatch($user);

        if ($interPushMatchUserInfo == 3) {
            return $this->renderJson([], 200, '今天匹配次数用完！');
        } elseif (is_array($interPushMatchUserInfo)) {
            return $this->interPushMatchUserInfo($interPushMatchUserInfo);
        }
        return $this->renderJson([], 0, '没有匹配到，请重新匹配！');
    }

    /**
     * 获取用户分享记录
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function getCompleteInterPushMatchUserList(Request $request)
    {
        $user = $request->user();
        $data = [];
        $items = InterPushMatchUser::where("user_id", $user->id)
            ->orWhere("match_user_id", $user->id)
            ->where(['match_share' => 1])->orWhere(["share" => 1])
            ->orderBy('updated_at', 'desc')
            ->paginate(10);

        $partition["count"] = $items->total();
        $partition["page"] = $items->currentPage();
        $partition["pageSize"] = $items->lastPage();

        foreach ($items as $item) {
            $data[] = [
                'id' => $item['id'],
                'match_user_id' => $item['match_user_id'] == $user->id ? $item['user_id'] : $item['match_user_id'],
                'interpush_type' => $item['match_user_id'] == $user->id ? $item['interpush_type'] : $item['match_interpush_type'],
                'interpush_article' => $item['match_user_id'] == $user->id ? $item['hutui_article'] : $item['match_interpush_article'],
                'is_share' => $item['match_user_id'] == $user->id ? 1 : $item["match_share"],
                'created_at' => $item['updated_at'],
                'type' => $item['match_user_id'] == $user->id ? 1 : 2
            ];
        }

        return $this->interPushMatchUserInfo($data, $partition);
    }

    /**
     * 修改分享状态
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function updateInterPushMatchUserShare(Request $request)
    {

        if ($type = $request->input('type')) {
            $item = InterPushMatchUser::where('id', $request->input('id'))->first();
            $item->match_share = 1;
            $item->match_share_time = date("Y-m-d H:i:s");

        } else {
            $item = InterPushMatchUser::where('id', $request->input('id'))->first();
            $item->share = 1;
            $item->share_time = date("Y-m-d H:i:s");
        }
        if ($item) {

            $item->save();
            return $this->success('分享成功！');
        }
        return $this->error('数据错误');
    }

    /**
     * 获取被动分享
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function getPassiveInterPushMatchUserList(Request $request)
    {
        $user = $request->user();

        if (!$type = $request->input('type')) {
            $type = 0;
        }
        $data = [];
        $items = InterPushMatchUser::where('match_user_id', $user->id)->where('match_share', $type)->orderBy('created_at', 'desc')->get();
        if (!$items) {
            // 判断别人是否还可以匹配
            $bool = InterPushMatchUser::where('match_user_id', $user->id)->where('match_share', $type)->where("created_at", 'like', "%" . date("Y-m-d", time()) . "%")->count();
            return $this->InterPushRenderJson([], 200, '没有数据', $bool ? true : false);
        }

        foreach ($items as $item) {
            $data[] = [
                'id' => $item['id'],
                'match_user_id' => $item['user_id'],
                'interpush_type' => $item['interpush_type'],
                'interpush_article' => $item['hutui_article'],
                'is_share' => $item['share'],
                'created_at' => $item['created_at']
            ];
        }
        return $this->interPushMatchUserInfo($data);
    }


    /**
     * 返回互推列表数据
     * @param $data
     * @return \Illuminate\Http\Response
     */
    public function interPushMatchUserInfo($data, $partition = [])
    {
        if (!$data) {
            return $this->success();
        }
        $items = [];
        for ($i = 0; $i < count($data); $i++) {
            if ($data[$i]['interpush_type'] == 2) {
                $article = DB::table('articles')->where('id', $data[$i]['interpush_article'])->first();
                $article = [
                    'uuid' => $article->id,
                    'title' => $article->title,
                    'cover_path' => $article->cover_path,
                    'created_at' => $article->created_at,
                    'actual_pageviews' => $article->actual_pageviews
                ];
            } else {
                $template = DB::table("personal_page_template_user")->select("id", "user_id", "template_id", "cover", "content","title", "created_at", "popularity", "type")->where("id", $data[$i]['interpush_article'])->first();
                $article = $template;
            }

            $card = Cards::where('user_id', $data[$i]['match_user_id'])->first();
            $exist_card = true;
            if ($card == null) {
                $exist_card = false;
            }

            $items[] = [
                'id' => $data[$i]['id'],
                'user_id' => $data[$i]['match_user_id'],
                'exist_card' => $exist_card,
                'name' => User::getUserName($data[$i]['match_user_id']),
                'head_portrait' => UserDetail::head_portrait($data[$i]['match_user_id']),
                'weixin_img' => InterPushUserInfo::getUserWeiXinImg($data[$i]['match_user_id']),
                'interpush_type' => $data[$i]['interpush_type'],
                'interpush_article' => $data[$i]['interpush_article'],
                'article' => $article,
                'is_share' => $data[$i]['is_share'],
                'created_at' => $data[$i]['created_at']->format('Y-m-d H:i:s'),
                'type' => isset($data[$i]['type']) ? $data[$i]['type']:'',
            ];
        }
        if (!$items) {
            return $this->renderJson([], 0, '没有数据');
        }
        return $this->InterPushRenderJson($items, 0, "", $partition ? $partition : "");
    }

    /**
     * 提醒
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function remind(Request $request)
    {
        $this->validate($request, [
            'match_id' => 'required',
        ], [
            'required' => '参数错误'
        ]);
        $user = $request->user();
        $match_id = $request->input('match_id');
        $match = (new \App\Model\InterPushMatchUser)->find($match_id);
        $type = $request->input('type');
        //判断当前登录用户身份
        $remind_user_id = $match->match_user_id;//被提醒人id
        $is_share = $match->match_share;//是否分享
        if ($match->user_id != $user->id) {//不是自己匹配就是别人推我，转换身份
            //别人推我推别人
            $remind_user_id = $match->user_id;
            $is_share = $match->share;
        }

        $msg = InterPushUserMessageRemind::where('user_id', $user->id)->where('remind_user_id', $remind_user_id)->where('interpush_match_user_id', $match_id)->first();

        if ($is_share == 1) {
            $this->fail('对方已经分享', 200);
        }
        if ($msg == null) {
            $msg = new InterPushUserMessageRemind();
            $msg->user_id = $user->id;
            $msg->remind_user_id = $remind_user_id;
            $msg->interpush_match_user_id = $match_id;
            $msg->remind_time = date('Y-m-d H:i:s');
            //提醒
            $userDetail = UserDetail::where('user_id', $remind_user_id)->first();
            WeChat::sendWeChatMsg($userDetail->open_id, env('WECHAT_OFFICIAL_TEMPLATE_ID'), env('INTER_PUSH_URL'), [
                'first' => '互推圈提醒',
                'keyword1' => $user->detail->wechat_name . ' 向你发起了互推请求，快去互推圈相互分享吧！',
                'remark' => '点击查看详情'
            ]);
            $msg->save();
        } else {

            //判断上一次时间，间隔一小时
            if ($msg->remind_time == null) {
                //判断创建时间
                if (strtotime('+1 hour', strtotime($msg->created_at)) > time()) {
                    return $this->fail('一小时内只能提醒一次');
                }
            } else {
                if (strtotime('+1 hour', strtotime($msg->remind_time)) > time()) {
                    return $this->fail('一小时内只能提醒一次');
                }
            }
            //提醒
            $userDetail = UserDetail::where('user_id', $remind_user_id)->first();
            $username = $user->detail->wechat_name;
            if ($user->card) {
                if ($user->card->user_name) {
                    $username = $user->card->user_name;
                }
            }
            WeChat::sendWeChatMsg($userDetail->open_id, env('WECHAT_OFFICIAL_TEMPLATE_ID'), env('INTER_PUSH_URL'), [
                'first' => '互推圈提醒',
                'keyword1' => $username . ' 向你发起了互推请求，快去互推圈相互分享吧！',
                'remark' => '点击查看详情'
            ]);
            $msg->remind_time = date('Y-m-d H:i:s');
            $msg->save();
        }
        return $this->success();
    }

    public function report_info(Request $request)
    {
        $match_id = $request->input('match_id');
        $msg = InterPushMatchUser::find($match_id);

        $f = strtotime('+3 hour', strtotime($msg->created_at));
        $time = 0;
        //过期时间大于当前时间
        if ($f > time()) {
            $time = $f - time();//剩余
        }

        return $this->renderJson([
            'remaining_time' => $time,
            'item' => [
                0 => '标题党',
                1 => '涉嫌违法犯罪',
                2 => '低俗色情',
                3 => '政治敏感',
                4 => '侮辱谩骂',
                5 => '造谣传谣,涉嫌欺诈',
                6 => '未经授权',
                7 => '侵权',
            ]
        ]);
    }

    public function report(Request $request)
    {
        $user = $request->user();
        $match_id = $request->input('match_id');
        $match = InterPushMatchUser::find($match_id);
        $match_user = $match->match_user_id;
        if ($user->id != $match->user_id) {
            $match_user = $match->user_id;
        }
        //根据场景选择用户
        $o = DB::table('interpush_report')->where('user_id', $user->id)->where('match_id', $match_user)->first();
        if ($o != null) {
            return $this->fail('你已经举报过了');
        }
        if ($match == null) {
            return $this->fail('找不到匹配记录');
        }
        if ($request->input('type') == 0) {
            if (strtotime('+3 hour', strtotime($match->created_at)) > time()) {
                return $this->fail('分享后3小时才能举报');
            }
            $r = DB::table('interpush_report')->insert([
                'user_id' => $user->id,
                'match_id' => $match_user,
                'type' => 0,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            if (!$r) {
                return $this->error();
            }
        } elseif ($request->input('type') == 1) {
            $r = DB::table('interpush_report')->insert([
                'user_id' => $user->id,
                'match_id' => $match_user,
                'type' => 1,
                'item' => $request->input('item'),
                'supplement' => $request->input('supplement'),
                'created_at' => date('Y-m-d H:i:s')
            ]);
            if (!$r) {
                return $this->error();
            }
        }
        return $this->success();
    }

    public function testRedis()
    {
        $interpush_match_users = \DB::table('interpush_match_user')->pluck('id');


        foreach ($interpush_match_users as $value) {
            $interpush_match_user = InterPushMatchUser::find($value);

            if ($interpush_match_user->interpush_type == 1) {

                if ($personal_page_template_user = \DB::table('personal_page_template_user')->where('user_id', $interpush_match_user->user_id)->limit(1)->get())
                    $interpush_match_user->hutui_article = $personal_page_template_user[0]->id;

            }
            if ($interpush_match_user->match_interpush_type == 1) {
                if ($template_user = \DB::table('personal_page_template_user')->where('user_id', $interpush_match_user->match_user_id)->limit(1)->get())
                    $interpush_match_user->match_interpush_article = $template_user[0]->id;
            }
            $interpush_match_user->save();
            echo $value . '<br/>';
        }
        echo 'ok';
    }

}
